#!/bin/sh
currentpath=$(pwd);						                               	#当前执行脚本所在目录
shellPath=$(cd `dirname $0`; pwd); 			                      		#Shell脚本所在目录
rsaPubName=/home/git/.ssh/authorized_keys                                  #公钥文件所在位置
gitosisUrl=https://github.com/res0nat0r/gitosis.git           #gitosis下载地址
gitRepoDir=${gitRepoDir:-/home/git/repositories}              #git仓库地址
gitRepoName=${gitRepoName:-jpanda.git}                        #git仓库名称
#=================================================
#========         日志脚本引用代码         ==========
#=================================================
logshExist=$(`ls ./log.sh &>/dev/null`; echo $?);			            #日志脚本文件是否存在
downLoaded=0;								                            #是否下载过脚本文件,如果下载过,无论成功失败都不会再次下载.
if [ $logshExist -gt 0 -a  $downLoaded -eq 0 ]
  then
    wget -Ncq http://gitee.com/topanda/note/raw/master/linux/log.sh &>/dev/null;		#下载日志脚本
    downLoaded=1;							                            #重置下载标记
fi
chmod u+x log.sh							                            #修改日志脚本执行权限
logshExist=$(`ls ./log.sh &>/dev/null`; echo $?);
function log(){								                            #如果不存在日志文件,默认什么都不做.
  if [  $logshExist -eq 0 ]
    then
    logPath=$shellPath/log.sh
    $logPath $*;
  fi
}
#================================================
#================================================
#=========    错误日志监听方法    ===============

function listionErr(){
while read line;do log WARN $line;done;
}
#==========   日志脚本引用代码 END   ===============
#================================================
# 进入脚本执行目录.
log INFO "安装gitosis..."
#安装依赖
log INFO "\033[32;05m 检查安装依赖项:python-setuptools... \033[0m"
yum -y -q install python-setuptools | listionErr
log INFO "cloneGitosis项目"
log INFO "gitosis下载地址是:$gitosisUrl"
log INFO "\033[32;05m 下载gitosis... \033[0m"
git clone -q $gitosisUrl | listionErr
cd ./gitosis
log INFO "\033[32;05m 安装gitosis... \033[0m"
python setup.py install >/dev/null
log INFO "git仓库地址(默认安装在/home/git/repositories下)";
#read -t 20 -p "请输入仓库名称(默认为jpanda.git)[20s]:" gitRepoName
log INFO "仓库名称(默认为jpanda.git)"
ls $gitRepoDir 2>/dev/null  1>/dev/null || mkdir -p $gitRepoDir && log INFO "创建了新的目录:$gitRepoDir";
log INFO "进入$gitRepoDir目录下..."
cd $gitRepoDir
ls $gitRepoName 2>/dev/null  1>/dev/null || mkdir -p $gitRepoName && log INFO "创建了git仓库目录:$gitRepoName"
#配置gitosis
chown -R git:git /home/git
#SSH 免密码登录并交给gitosis管理.
su git<<EOF
gitosis-init <~/.ssh/authorized_keys
chmod 755 /home/git/repositories/gitosis-admin.git/hooks/post-update
exit
EOF
log INFO "git仓库地址(默认安装在/home/git/repositories下)";
if [ $gitRepoDir != /home/git/repositories ]
  then ln -s $gitRepoDir /home/git/repositories
fi
mkdir -p /home/git/repositories/gitosis-admin.git/keys
cp $rsaPubName  /home/git/repositories/gitosis-admin.git/keys/git.pub
log WARN "3.脚本在执行完毕后,不会删除gitosis相关文件."
log WARN "4.脚本生成密钥的默认用户为:git,证书密码为:123456."
